package com.diorsunion.hedge.web.controller;

import com.diorsunion.hedge.common.ServiceResult;
import com.diorsunion.hedge.io.Message;
import com.diorsunion.hedge.io.MessageType;
import com.diorsunion.hedge.io.Remoter;
import com.diorsunion.hedge.io.IOServer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Set;

/**
 * Created by harley-dog on 2016/5/17.
 */
@Controller
@Scope("prototype")
@RequestMapping("/server")
public class ServerController {

    @Resource @Qualifier("nettyServer")
    IOServer serverHandler;

    @RequestMapping(value = "/status", method = {RequestMethod.GET})
    @ResponseBody
    public ServiceResult status() {
        return serverHandler.status();
    }

    @RequestMapping(value = "/start", method = {RequestMethod.GET})
    @ResponseBody
    public ServiceResult start(@RequestParam(required = true) Integer port) {
        return serverHandler.start(port);
    }

    @RequestMapping(value = "/stop", method = {RequestMethod.GET})
    @ResponseBody
    public ServiceResult stop() {
        return serverHandler.stop();
    }

    @RequestMapping(value = "/write", method = {RequestMethod.GET})
    @ResponseBody
    public JsonResult writeAll(@RequestParam String param) {
        Message<String> message = Message.genMessage(MessageType.Test,param);
        serverHandler.write(message);
        return JsonResult.succResult();
    }
    @RequestMapping(value = "/{id}/write", method = {RequestMethod.GET})
    @ResponseBody
    public JsonResult write(@PathVariable String id, @RequestParam String param) {
        Message<String> message = Message.genMessage(MessageType.Test,param);
        serverHandler.write(id,message);
        return JsonResult.succResult();
    }


    @RequestMapping(value = "/all", method = {RequestMethod.GET})
    @ResponseBody
    public JsonResult all() {
        Set<Remoter> remoters = serverHandler.allRemoters();
        return JsonResult.succResult(remoters);
    }
}
